package com.example.mplayer.player

import android.content.Context
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.TransferListener
import java.security.KeyFactory
import java.security.spec.PKCS8EncodedKeySpec
import android.util.Base64
import androidx.media3.common.util.UnstableApi
import java.security.PrivateKey

@UnstableApi
class CustomHlsDataSourceFactory(
    private val context: Context,
    private val privateKeyString: String
) : DataSource.Factory {
    private var listener: TransferListener? = null
    private val privateKey: PrivateKey = loadPrivateKey(privateKeyString)

    private fun loadPrivateKey(privateKeyString: String): PrivateKey {
        val privateKeyPEM = privateKeyString
            .replace("-----BEGIN PRIVATE KEY-----", "")
            .replace("-----END PRIVATE KEY-----", "")
            .replace("\n", "")
        
        val keyBytes = Base64.decode(privateKeyPEM, Base64.DEFAULT)
        val keySpec = PKCS8EncodedKeySpec(keyBytes)
        val keyFactory = KeyFactory.getInstance("RSA")
        return keyFactory.generatePrivate(keySpec)
    }

    override fun createDataSource(): DataSource {
        val defaultDataSourceFactory = DefaultDataSource.Factory(
            context,
            DefaultHttpDataSource.Factory()
        )
        
        val upstreamDataSource = defaultDataSourceFactory.createDataSource()
        return EncryptionKeyDataSource(upstreamDataSource, privateKey)
    }
} 